package com.uzhie.web.controller.websocket;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by TangFei on 2018/8/10.
 * 自定义bean命名规则
 */
public class AnnotationBeanNameGenerator extends org.springframework.context.annotation.AnnotationBeanNameGenerator {

    private Logger logger = Logger.getLogger(this.getClass());

    @Override
    protected String buildDefaultBeanName(BeanDefinition definition) {
        return super.buildDefaultBeanName(definition) + "Socket";
    }

    @Override
    public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
        return super.generateBeanName(definition, registry);
    }

    @Override
    protected String determineBeanNameFromAnnotation(AnnotatedBeanDefinition annotatedDef) {
        AnnotationMetadata metadata = annotatedDef.getMetadata();
        Set types = metadata.getAnnotationTypes();
        String beanName = null;
        Iterator var5 = types.iterator();
        while (var5.hasNext()) {
            String type = (String) var5.next();
            Map<String, Object> annotationAttributes = metadata.getAnnotationAttributes(type);
            if (isStereotypeWithNameValue(type, types, annotationAttributes)) {
                Object value = annotationAttributes.get("name");
                if (value instanceof String) {
                    String strVal = (String) value;
                    if (StringUtils.hasLength(strVal)) {
                        if (beanName != null && !strVal.equals(beanName)) {
                            throw new IllegalStateException("Stereotype annotations suggest inconsistent component names: \'" + beanName + "\' versus \'" + strVal + "\'");
                        }
                        beanName = strVal;
                    }
                }
            }
        }
        return beanName;
    }

    @Override
    protected boolean isStereotypeWithNameValue(String annotationType, Set<String> metaAnnotationTypes, Map<String, Object> attributes) {
        boolean isStereotype = annotationType.equals("SocketController") || metaAnnotationTypes != null && metaAnnotationTypes.contains("SocketController") || annotationType.equals("javax.annotation.ManagedBean") || annotationType.equals("javax.inject.Named");
        return isStereotype && attributes != null && (attributes.containsKey("value") || attributes.containsKey("name"));
    }
}
